import { Modal } from 'ant-design-vue';
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';

import BiliLayout from '@/components/BiliLayout.vue';
import useAuthStore from '@/stores/auth.store';
import { hasPermission } from '@/utils/haveIntersection';
import { filterTree } from '@/utils/tree';
import routesAuth from '@/views/auth-config';
import routesHome from '@/views/home-page';

const routes: RouteRecordRaw[] = [...routesHome];

const initRouter = () => {
  const authStore = useAuthStore();
  const result = [];
  const children = filterTree(
    routes,
    (route) => !hasPermission(
      authStore.permissions,
        (route?.meta?.permissions || []) as string[],
    ),
  );
  if (authStore.roles.includes('admin')) {
    children.push(...routesAuth);
  }
  if (children.length === 0) {
    children.push({
      path: '/:pathMatch(.*)*',
      component: () => import('@/views/error-page/ErrorForbidden.vue'),
    } as any);
  } else {
    result.push({
      path: '',
      redirect: children[0].path,
    });
  }
  result.push({
    path: '/',
    component: BiliLayout,
    children,
  });
  const router = createRouter({
    history: createWebHistory(import.meta.env.DEV ? '/' : '/'),
    routes: result,
  });

  router.beforeEach(() => {
    Modal.destroyAll();
  });

  return router;
};

export default initRouter;
